package com.lagou.webwork.servlet; /**
 * @author sjp
 * @date 2021/5/26 19:34
 * @description
 */

import com.lagou.webwork.model.Result;
import com.lagou.webwork.model.User;
import com.lagou.webwork.service.UserService;

import javax.print.attribute.standard.MediaSize;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import javax.swing.plaf.synth.SynthListUI;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

@WebServlet(name = "LoginServlet", value = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取post参数
        String name = request.getParameter("name");
        String pwd = request.getParameter("password");

        //创建Service对象，执行login方法
        UserService userService = new UserService();
        User user = userService.login(new User(name, pwd));

        //用户为空表示没找到登陆失败，不为空表示登陆成功
        if (user == null){
            var result = new Result<User>("200", new LinkedList<User>(),0, "用户名或密码错误!");
            request.setAttribute("resultModel", result);
        }else{
            List<User> userList = new LinkedList<>();
            userList.add(user);
            request.setAttribute("resultModel", new Result("200",userList,1, "登录成功"));

            //设置Cookie作用范围和时间
            Cookie userInfoCookie = new Cookie("userName", name);
            userInfoCookie.setMaxAge(7 * 24 * 60 * 60);
            userInfoCookie.setPath("/");
            response.addCookie(userInfoCookie);
        }

        //转发给login.jsp处理
        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }
}
